<template>
  <div>
    <el-card class="search-card">
      <basic-table-form
        ref="formData"
        :formColumns="FORM_ITEM_LIST"
        :dataSource="formData"
        :defaultExpandStatus="false"
        :handleSearchForm="handleQueryForm"
        @getFormData="getFormData"
        :colNumOfRow="4"
      >
      </basic-table-form>
    </el-card>
    <el-card class="table-card">
      <basic-table
        :showSelectCol="false"
        :loading="tableInfo.loading"
        :columns="tableInfo.columns"
        :dataSource="tableInfo.list"
        :pagination="pagination"
        :tableHeight="460"
        showActionCol
        :actionColWidth="170"
        :actionRender="renderTableBtnAction"
        @pageChange="handlePageChange"
        @pageSizeChange="handlePageSizeChange"
      >
        <div slot="content_context">
          <el-button
            v-if="showBtn('导出') && supplierExportConfig.inner"
            :loading="exportLoading"
            size="mini"
            type="primary"
            icon="el-icon-download"
            @click="handleExport"
            >导出</el-button
          >
        </div>
      </basic-table>
    </el-card>
    <ConvertSupplierDialog
      ref="convertSupplierDialog"
      :convertType="convertType"
      :supplier="selectCurrentRow"
      :isReport="true"
      :dialogVisible="convertVisible"
      @handleSubmit="handleDialogSubmit"
      @handleClose="handleDialogClose"
    />
    <!-- 暂不处理 -->
    <NotProcess
      :visible.sync="notProcessVisible"
      :selectData="selectCurrentRow"
      @getTableData="getTableData"
    />
  </div>
</template>
<script>
import BasicTableForm from '@/components/supplier/BasicForm';
import BasicTable from '@/components/supplier/BasicTable';
import ConvertSupplierDialog from '@supplier/components/convertSupplierDialog';
import NotProcess from '../components/NotProcess';
import { FORM_ITEM_LIST, TABLE_COLUMNS } from './constants';
import BasicPage from '@/mixins/supplier/basicPage';
import Dict from '@/mixins/supplier/dict';
import { createExcelByExport, setAuthBtnId } from '@/utils/bizUtils';
import { getTableAction } from '@supplier/utils/btnsUtils';
import { demoteSupplier } from '@/api/supplier/management/common';
import { supplierPreConvertCheck } from '@/api/supplier/components';
import { queryPotentialOperationService, exportPotentialOperationService } from '@api/supplier/innerManagement/potentialSupplier';

export default {
  mixins: [ BasicPage, Dict ], // 分页数据及方法 表单基础方法
  components: {
    BasicTableForm,
    BasicTable,
    ConvertSupplierDialog,
    NotProcess
  },
  data () {
    return {
      notProcessVisible: false,
      FORM_ITEM_LIST,
      formData: {
        supplierCode: '',
        supplierName: '',
        supplierType: null,
        managementAreaId: '',
        personName: '',
        disposeName: '',
        disposeType: null,
        backlogReason: '',
        belongDepartment: null,
      },
      selectCurrentRow: {},
      convertVisible: false,
      convertType: '1',
    };
  },
  created () {
    this.tableInfo.columns = TABLE_COLUMNS
    this.getTableData();
  },
  methods: {
    renderTableBtnAction (h, { row }) {
      // 待办状态 0未处理, 1待处理， 2已处理
      if (row.backlogStates != 2) {
        const actionList = [
          { label: '转线索', authLabel: '转为线索', method: () => this.handleConvertSuppliers(row, '3'), hasAuth: true },
          { label: '淘汰', authLabel: '淘汰供应商', method: () => this.handleEliminateSuppliers(row, '10'), hasAuth: true },
          { label: '暂不处理', method: this.handleNotProcess, hasAuth: true },
        ]
        if (row.backlogReason == '近3个月采购频次大于5次') {
          actionList.unshift({
            label: '转合格',
            authLabel: '转为合格',
            method: () => this.handleConvertSuppliers(row, 'qualified'),
            hasAuth: true
          })
        }
        return getTableAction({ h, row, actionList, showBtn: this.showBtn });
      }
    },
    // 暂不处理
    handleNotProcess (row) {
      this.selectCurrentRow = row;
      this.notProcessVisible = true;
    },
    // 获取表格数据
    async getTableData () {
      let data = {
        ...this.formData,
        ...this.pagination
      };
      setAuthBtnId()
      const res = await queryPotentialOperationService(data, state => { this.tableInfo.loading = state })
      if (res) {
        const { records, total } = res.result;
        this.tableInfo.list = records;
        this.pagination.total = total;
      }
    },
    // 导出
    async handleExport () {
      const res = await exportPotentialOperationService(this.formData, state => { this.exportLoading = state })
      if (res) {
        createExcelByExport({ excelTitle: '潜在供应商升降级待办列表', res })
      }
    },
    // 转化供应商 type 5 转潜在 3 转线索
    async handleConvertSuppliers (data, type) {
      const { supplierId, backlogId } = data
      const { result } = await supplierPreConvertCheck({ supplierId, operateType: type == 5 ? 8 : 5 })
      if (result === '1') {
        if (type === 'qualified') {
          this.$router.push({
            name: 'corventPotential2Qualified',
            query: { id: supplierId, backlogId }
          });
        } else {
          // 潜在转线索
          this.convertType = type
          this.selectCurrentRow = data
          this.convertVisible = true
        }
      } else {
        this.$message.error(result)
      }
    },
    // 淘汰供应商
    handleEliminateSuppliers (data, type) {
      this.convertType = type
      this.selectCurrentRow = data
      this.convertVisible = true
    },
    // 转化供应商提交
    handleDialogSubmit (data) {
      if ((this.convertType === '3' || this.convertType === '5') && data) {
        const { causeType, causeDescription, supplierId, supplierCode, supplierName, backlogId } = data
        const supplierBill = { causeType, causeDescription, supplierId, supplierCode, supplierName, supplierClassify: this.convertType === '3' ? 40899 : 40331 }
        const obj = { processDocumentOperateType: this.convertType === '3' ? 9 : 8, processDocumentStatus: 10, supplierBill, backlogId }
        demoteSupplier(obj).then((resp) => {
          if (resp && resp.status === '0') {
            this.$refs.convertSupplierDialog.close()
            this.$message.success('操作成功！')
          }
        }).finally(() => {
          this.$refs.convertSupplierDialog.updateLoadingState()
        })
        return
      }
      this.handleDialogClose()
    },
    // 关闭弹框
    handleDialogClose () {
      this.convertVisible = false
    },
  }
};
</script>
